import { Component } from '@angular/core';
import { IonicPage, NavController, NavParams, AlertController } from 'ionic-angular';
import { TabsPage } from '../tabs/tabs';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
// import { User } from './models/index';

import { LoginService } from './services/login.service'

/**
 * Generated class for the LoginPage page.
 *
 * See https://ionicframework.com/docs/components/#navigation for more info on
 * Ionic pages and navigation.
 */

@IonicPage()
@Component({
    selector: 'page-login',
    templateUrl: 'login.html',
})
export class LoginPage {
    login: FormGroup;
    message: string;
   
    constructor(
        private alertCtrl:AlertController,
        public service:LoginService,
        public navCtrl: NavController, 
        public navParams: NavParams,
        public fb: FormBuilder,
        ) {
            this.login = this.fb.group({
                'username': ['', Validators.compose([Validators.required])],
                'password': ['', Validators.compose([Validators.required])]
              });
    }

    ionViewDidLoad() {
    }

    onSubmit() {
        const username = this.login.get('username').value;
        const password = this.login.get('password').value;

        this.service.login(username, password)
        .subscribe(data => {
            // window.localStorage.setItem('username',data.username);


          sessionStorage.setItem('token', data.id);
          sessionStorage.setItem('username', data.username);
          // sessionStorage.setItem('role', data.role);
          this.message = null;
          // this.afterLogin(username);
          this.navCtrl.push(TabsPage);
        }, (err) => {
          switch (err.status) {
            case 401:
            let alert = this.alertCtrl.create({
                title:'提示信息',
                 subTitle:'未授权的用户名',
                 buttons:['确定']
              })
              alert.present();
              break;

              case 403:
              let alert2 = this.alertCtrl.create({
                  title:'提示信息',
                   subTitle:'密码错误',
                   buttons:['确定']
                })
                alert2.present();
                break;

                case 404:
                let alert3 = this.alertCtrl.create({
                    title:'提示信息',
                     subTitle:'请输入正确的用户名和密码',
                     buttons:['确定']
                  })
                  alert3.present();
                  break;



            default:
            let alert4 = this.alertCtrl.create({
                title:'提示信息',
                 subTitle:'未知错误',
                 buttons:['确定']
        })
         alert4.present();
              break;
          }




        });
        
    }


}
